package com.hope.mychat.core.rule;

import com.hope.mychat.core.MyChat;
import com.hope.mychat.domain.vo.Message;
import com.hope.mychat.support.ChatType;
import com.hope.mychat.util.DateUtil;
import com.hope.mychat.util.RedisUtil;

import javax.websocket.EncodeException;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * @author ZWH
 */
public class Chat extends Base {
    public Chat(Message message) {
        super(message);
    }

    public void handle() throws IOException, EncodeException {
        if (ChatType.CHAT_TYPE_PRIVATE.getValue() == message.getChatType()) {
            // 私聊
            sessionTo = MyChat.LIVING_SESSIONS_CACHE.get(message.getToId());
            if (sessionTo == null) {
                return;
            }
            setMessage();
            sessionTo.getBasicRemote().sendObject(message);
        } else if (ChatType.CHAT_TYPE_PUBLIC.getValue() == message.getChatType()) {
            // 群聊
            int chatroomId = message.getChatroomId();
            if (chatroomId == 0) {
                return;
            }
            // TODO 根据chatroomId获取群聊成员并发送
            String uidStr = (String)redisUtil.hGet("CHATROOM_MEMBER_UIDS", String.valueOf(chatroomId));
            String[] uidArr = uidStr.split(",");
            setMessage();
            for (String uid : uidArr) {
                sessionTo = MyChat.LIVING_SESSIONS_CACHE.get(uid);
                if (sessionTo == null || uid == message.getFromId()) {
                    continue;
                }
                sessionTo.getBasicRemote().sendObject(message);
            }
        }
    }

    private void setMessage() {
        UUID uuid = UUID.randomUUID();
        String uuidStr = uuid.toString();
        message.setMsgId(uuidStr);
        message.setCreateTime(DateUtil.getCurSecond());
    }
}
